package com.example.interceptor;

import com.alibaba.fastjson.JSON;
import com.example.common.BaseContext;
import com.example.constant.BaseUrls;
import com.example.common.Re;
import com.example.utils.PathUtils;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户登录拦截器
 *
 * @author czx
 * @since 2022/5/13 18:43
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        Long userId = (Long) request.getSession().getAttribute("user");
        Long employeeId = (Long) request.getSession().getAttribute("employee");

        String requestURI = request.getRequestURI();
        log.info("本次页面请求:{}", requestURI);

        // 5、判断用户登录状态
        if (userId != null) {
            // 5-1、检查是否访问特定员工页面
            if (PathUtils.check(BaseUrls.employeeUrls, requestURI)) {
                log.info("员工未登录");
                response.getWriter().write(JSON.toJSONString(Re.error("NOTLOGIN")));
                return false;
            }
            BaseContext.setCurrentId(userId);
            return true;
        }
        // 6、判断员工登录状态
        if (employeeId != null) {
            // 6-1、检查是否访问特定用户页面
            if (PathUtils.check(BaseUrls.userUrls, requestURI)) {
                log.info("用户未登录");
                response.getWriter().write(JSON.toJSONString(Re.error("NOTLOGIN")));
                return false;
            }
            BaseContext.setCurrentId(employeeId);
            return true;
        }


        log.info("需要处理的页面请求: {}", requestURI);
        log.info("拦截到的请求,{}", requestURI);
        response.getWriter().write(JSON.toJSONString(Re.error("NOTLOGIN")));
        return false;
    }
}
